package com.xingyu.springbootlearn.controller;

import com.xingyu.springbootlearn.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘星宇
 * @version 1.0
 * @date 2020/10/9 15:38
 */
@RestController
@CrossOrigin
public class SmsApiController {

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone){
        String code = redisTemplate.opsForValue().get(phone); // 查看Redis数据库是否存在该手机号获取的验证码
        if(!StringUtils.isEmpty(code)){
            return phone + ":" + code + "已存在，还未过期！";
        }
        code = UUID.randomUUID().toString().substring(0,4); // Redis中不存在则随机自动生成
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = sendSms.send(phone, "SMS_204127841", param);
        if(isSend){
            redisTemplate.opsForValue().set(phone, code, 60, TimeUnit.SECONDS); //设置过期时间，60s
            return phone + ":" + code + "发送成功！";
        }else{
            return "发送失败！";
        }
    }
}
